package com.shycloud.mido.member.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.member.api.dto.MemberDTO;
import com.shycloud.mido.member.api.entity.ErpActivityInfo;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MemberDetailInfo;
import com.shycloud.mido.member.api.entity.MemberLevel;
import com.shycloud.mido.member.api.entity.MemberRole;
import com.shycloud.mido.member.api.entity.MemberSign;
import com.shycloud.mido.member.api.enums.MessageCodeEnum;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.vo.AttestationVO;
import com.shycloud.mido.member.api.vo.MemberDetailVO;
import com.shycloud.mido.member.api.vo.MemberVO;
import com.shycloud.mido.member.api.vo.MembershipInfoVO;
import com.shycloud.mido.member.api.vo.MembershipVO;
import com.shycloud.mido.member.api.vo.TeacherInfoVO;
import com.shycloud.mido.member.mapper.ErpActivityInfoMapper;
import com.shycloud.mido.member.mapper.MemberDetailInfoMapper;
import com.shycloud.mido.member.mapper.MemberLevelMapper;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.mapper.MemberRoleMapper;
import com.shycloud.mido.member.mapper.MemberSignMapper;
import com.shycloud.mido.member.service.MemberService;

import cn.hutool.core.util.IdUtil;
import lombok.AllArgsConstructor;

/**
 * 会员管理
 *
 * @author lxy
 * @date 2019-02-27 14:10:49
 */
@Service
@AllArgsConstructor
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
	private final MemberSignMapper memberSignMapper;
	private final MemberLevelMapper memberLevelMapper;
	private final MemberDetailInfoMapper memberDetailInfoMapper;
	private final MemberMapper memberMapper;
	private final MemberRoleMapper memberRoleMapper;
	private final CacheManager cacheManager;

	//ADDED
	private final ErpActivityInfoMapper erpActivityInfoMapper;


	/**
	 * 分页查询会员信息
	 *
	 * @param page      分页对象
	 * @param memberDTO 参数列表
	 * @return
	 */
	@Override
	public IPage<MemberVO> getMemberVosPage(Page page, MemberDTO memberDTO) {
		return baseMapper.getMemberVosPage(page, memberDTO);
	}

	/**
	 * 通过id锁定会员
	 *
	 * @param ids ids
	 * @return
	 */
	@Override
	public boolean lockByIds(List<String> ids) {
		return baseMapper.lockByIds(ids);
	}

	/**
	 * 通过id解锁会员
	 *
	 * @param ids ids
	 * @return
	 */
	@Override
	public boolean unlockByIds(List<String> ids) {
		return baseMapper.unlockByIds(ids);
	}

	/**
	 * 通过id删除会员
	 *
	 * @param ids ids
	 * @return
	 */
	@Override
	public boolean deleteByIds(List<String> ids) {
		return baseMapper.deleteByIds(ids);
	}

	/**
	 * 通过id查询关联家长
	 *
	 * @param id id
	 * @return
	 */
	@Override
	public List<Member> getAssociatedParents(String id) {
		return baseMapper.getAssociatedParents(id);
	}

	/**
	 * 通过id查询关联学生
	 *
	 * @param id id
	 * @return
	 */
	@Override
	public List<Member> getAssociatedStudents(String id) {
		return baseMapper.getAssociatedStudents(id);
	}

	/**
	 * 解绑会员
	 *
	 * @param studentId studentId
	 * @param parentId  parentId
	 * @return
	 */
	@Override
	public boolean unbindMember(String parentId, String studentId) {
		return baseMapper.unbindMember(parentId, studentId);
	}

	/**
	 * 通过id获取会员身份
	 *
	 * @param id 会员Id
	 * @return List<MembershipVO>
	 */
	@Override
	public List<MembershipVO> getMembership(String id) {
		return baseMapper.getMembership(id);
	}

	/**
	 * 通过id获取认证身份
	 *
	 * @param id 会员Id
	 * @return R List
	 */
	@Override
	public List<AttestationVO> getAttestation(String id) {
		return baseMapper.getAttestation(id);
	}

	/**
	 * 通过id获取教师信息
	 *
	 * @param id
	 * @return
	 */
	@Override
	public List<TeacherInfoVO> getTeacherInfo(String id) {
		return baseMapper.getTeacherInfo(id);
	}

	/**
	 * 注册会员
	 *
	 * @param member 会员信息
	 * @return
	 */
	@Override
	public R saveMember(Member member) {
		Member m;
		// 校验用户名
		QueryWrapper<Member> queryUsername = new QueryWrapper<>();
		queryUsername.eq("username", member.getUsername()).eq("del_flag", Constant.DEL_FLAG);
		m = baseMapper.selectOne(queryUsername);
		if (m != null) {
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_106.getMessage()).setCode(MessageCodeEnum.MEMBER_ERROR_106.getCode());
		}
		// 校验手机号
		QueryWrapper<Member> queryPhone = new QueryWrapper<>();
		queryPhone.eq("phone", member.getPhone()).eq("del_flag", Constant.DEL_FLAG);
		m = baseMapper.selectOne(queryPhone);
		if (m != null) {
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_103.getMessage()).setCode(MessageCodeEnum.MEMBER_ERROR_103.getCode());
		}
		// 保存用户
		m = new Member();
		m.setUsername(member.getUsername());
		m.setShowname(member.getUsername());
		m.setPassword(ENCODER.encode(member.getPassword()));
		m.setPhone(member.getPhone());

		//ADDED
		//判断是否有打印劵赠送活动
		List<ErpActivityInfo> actList = erpActivityInfoMapper.selectEnabledActivities();
		if (actList == null || actList.size() == 0) {
			m.setPrintAmountGive(0);
		} else {
			int printAmount = actList.get(0).getFreeAmount();
			m.setPrintAmountGive(printAmount);
		}

		baseMapper.insert(m);
		// 根据手机号查询用户
		Member mem = baseMapper.selectOne(queryPhone);
		// 插入签到信息表
		MemberSign sign = new MemberSign();
		sign.setMemberId(mem.getId());
		memberSignMapper.insert(sign);
		// 插入会员等级表
		MemberLevel level = new MemberLevel();
		level.setLevelId("1");
		level.setMemberId(mem.getId());
		level.setPoints(0L);
		memberLevelMapper.insert(level);

		//赠送一个月高级VIP
		MemberRole memberRole = new MemberRole();
		memberRole.setMemberId(mem.getId());
		memberRole.setRoleCode(Constant.VIP_MEMBER);
		memberRole.setDelFlag(Constant.DEL_FLAG);
		memberRole.setCreateTime(LocalDateTime.now());
		memberRole.setStartTime(LocalDateTime.now());
		memberRole.setEndTime(LocalDateTime.now().plusMonths(1));
		memberRoleMapper.saveMemberRole(memberRole);
		return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
	}

	/**
	 * 通过id获取教师信息
	 *
	 * @param type
	 * @return
	 */
	@Override
	public List<String> getMemberIdlist(String type) {
		if (Constant.MEMBER_TYPE_ALL.equals(type)) {
			return baseMapper.getAllId();
		} else if (Constant.MEMBER_TYPE_JUNIOR.equals(type)) {
			return baseMapper.getJuniorMemberId();
		} else if (Constant.MEMBER_TYPE_SENIOR.equals(type)) {
			return baseMapper.getSeniorMemberId();
		} else if (Constant.MEMBER_TYPE_TEACHER.equals(type)) {
			return baseMapper.getTeacherId();
		} else if (Constant.MEMBER_TYPE_ORGAN_TEACHER.equals(type)) {
			return baseMapper.getOrganTeacherId();
		} else if (Constant.MEMBER_TYPE_ORGAN.equals(type)) {
			return baseMapper.getOrganUserId();
		} else if (Constant.MEMBER_TYPE_MASTER.equals(type)) {
			return baseMapper.getMasterId();
		}
		return null;
	}


	/**
	 * 后台管理注册用户
	 *
	 * @param vo 会员信息
	 * @return
	 */
	@Override
	public String adminSaveMember(MemberDetailVO vo) {
		// 校验用户名
		QueryWrapper<Member> queryUsername = new QueryWrapper<>();
		queryUsername.eq("username", vo.getUsername()).eq("del_flag", Constant.DEL_FLAG);
		Member member1 = baseMapper.selectOne(queryUsername);
		if (member1 != null) {
			if (StringUtils.isNotBlank(vo.getIsOrganTeacher()) && vo.getIsOrganTeacher().equals(Constant.ORGAN_TEACHER)) {
				memberMapper.updIsOrgan(member1.getId());
			}
			return member1.getId();
		}
		// 校验手机号
		QueryWrapper<Member> queryPhone = new QueryWrapper<>();
		queryPhone.eq("phone", vo.getPhone()).eq("del_flag", Constant.DEL_FLAG);
		member1 = baseMapper.selectOne(queryPhone);
		if (member1 != null) {
			if (StringUtils.isNotBlank(vo.getIsOrganTeacher()) && vo.getIsOrganTeacher().equals(Constant.ORGAN_TEACHER)) {
				memberMapper.updIsOrgan(member1.getId());
			}
			return member1.getId();
		}
		Member member = new Member();
		// 保存用户
		member.setId(vo.getMemberId());
		member.setUsername(vo.getUsername());
		member.setShowname(vo.getShowname());
		member.setRealName(vo.getRealName());
		member.setPassword(vo.getPassword());
		member.setPhone(vo.getPhone());
		member.setDelFlag(Constant.DEL_FLAG);
		member.setIsStaff(vo.getIsStaff());
		member.setIsOrganTeacher(vo.getIsOrganTeacher());
		baseMapper.insert(member);
		// 根据手机号查询用户
		Member mem = baseMapper.selectOne(queryPhone);
		// 插入签到信息表
		MemberSign sign = new MemberSign();
		sign.setMemberId(mem.getId());
		memberSignMapper.insert(sign);
		// 插入会员等级表
		MemberLevel level = new MemberLevel();
		level.setLevelId("1");
		level.setMemberId(mem.getId());
		level.setPoints(0L);
		memberLevelMapper.insert(level);
		//新建会员详情
		MemberDetailInfo info = new MemberDetailInfo();
		info.setMemberId(mem.getId());
		info.setAddress(vo.getAddress());
		info.setBirthday(vo.getBirthday());
		info.setCity(vo.getCity());
		info.setCityId(vo.getCityId());
		info.setProvince(vo.getProvince());
		info.setProvinceId(vo.getProvinceId());
		info.setSex(vo.getSex());
		info.setSignature(vo.getSignature());
		info.setCreateTime(LocalDateTime.now());
		info.setBigIconPath(vo.getBigIconPath());
		info.setMiddleIconPath(vo.getMiddleIconPath());
		info.setSmallIconPath(vo.getSmallIconPath());
		info.setLastCity(vo.getLastCity());
		info.setLastIp(vo.getLastIp());
		info.setLocationAddress(vo.getLocationAddress());
		info.setLastTime(vo.getLastTime());
		info.setLocationX(vo.getLocationX());
		info.setLocationY(vo.getLocationY());
		memberDetailInfoMapper.insert(info);
		return null;
	}

	/**
	 * 后台管理修改密码
	 *
	 * @param memberId 会员ID
	 * @param pwd      密码
	 * @return
	 */
	@Override
	public Boolean updPwd(String memberId, String pwd) {
		Member member = memberMapper.selectById(memberId);
		Cache cache = cacheManager.getCache("member_details");
		cache.evict(member.getUsername());
		cache.evict(member.getPhone());
		return memberMapper.updPwd(memberId, ENCODER.encode(pwd));
	}

	/**
	 * 更新会员是否注册机构
	 *
	 * @param memberId 会员ID
	 * @param is       是否注册机构 0-未注册, 1-已注册
	 * @return
	 */
	@Override
	public R isInstitution(String memberId, String is) {
		return new R<>(memberMapper.isInstitution(memberId, is), MessageCodeEnum.SUCCESS.getMessage());
	}

	/**
	 * 购买会员-信息
	 *
	 * @param memberId 会员Id
	 * @return MembershipInfoVO
	 */
	@Override
	public MembershipInfoVO membershipInfo(String memberId) {
		return memberMapper.membershipInfo(memberId);
	}

	/**
	 * 更新会员个推会员标识
	 *
	 * @param memberId 会员ID
	 * @param clientId 个推会员标识
	 */
	@Override
	public R updClientId(String memberId, String clientId) {
		return new R<>(memberMapper.updClientId(memberId, clientId), MessageCodeEnum.SUCCESS.getMessage());
	}

	/**
	 * 批量注册高级会员
	 *
	 * @param phoneList 会员电话号码
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public R testMember(List<Map<String, String>> phoneList) {
		Member m1;
		Member m2;
		List<String> unsaveList = new ArrayList<>();
		List<Member> memberList = new ArrayList<>();
		for (int i = 0; i < phoneList.size(); i++) {
			Member member = new Member();
			// 校验用户名
			QueryWrapper<Member> queryUsername = new QueryWrapper<>();
			QueryWrapper<Member> queryPhone = new QueryWrapper<>();
			queryUsername.eq("username", phoneList.get(i).get("phone")).eq("del_flag", Constant.DEL_FLAG);
			queryPhone.eq("phone", phoneList.get(i).get("phone")).eq("del_flag", Constant.DEL_FLAG);
			m1 = baseMapper.selectOne(queryUsername);
			m2 = baseMapper.selectOne(queryPhone);
			if (m1 == null && m2 == null) {
				member.setId(IdUtil.simpleUUID());
				member.setUsername(phoneList.get(i).get("phone"));
				member.setShowname(phoneList.get(i).get("phone"));
				member.setPassword(ENCODER.encode("123456"));
				member.setPhone(phoneList.get(i).get("phone"));
				member.setCreateTime(LocalDateTime.now());
				baseMapper.insert(member);
				memberList.add(member);
				// 插入签到信息表
				MemberSign sign = new MemberSign();
				sign.setMemberId(member.getId());
				memberSignMapper.insert(sign);
				// 插入会员等级表
				MemberLevel level = new MemberLevel();
				level.setLevelId("1");
				level.setMemberId(member.getId());
				level.setPoints(0L);
				memberLevelMapper.insert(level);
				MemberRole role = new MemberRole();
				role.setCreateTime(LocalDateTime.now());
				role.setStartTime(LocalDateTime.now());
				//开通会员天数
				long day = Long.parseLong(phoneList.get(i).get("day"));
				role.setEndTime(LocalDateTime.now().plusDays(day));
				role.setRoleCode(Constant.VIP_MEMBER);
				role.setMemberId(member.getId());
				role.setDelFlag(Constant.DEL_FLAG);
				memberRoleMapper.saveMemberRole(role);
			} else {
				MemberRole role = memberRoleMapper.selectOne(Wrappers
						.<MemberRole>query().lambda()
						.eq(MemberRole::getMemberId, m2.getId()).eq(MemberRole::getRoleCode, Constant.VIP_MEMBER));
				if (role != null) {
					role.setEndTime(LocalDateTime.now().plusDays(Long.parseLong(phoneList.get(i).get("day"))));
					memberRoleMapper.updMemberRole(role);
				} else {
					MemberRole role2 = new MemberRole();
					role2.setCreateTime(LocalDateTime.now());
					role2.setStartTime(LocalDateTime.now());
					//开通会员天数
					long day = Long.parseLong(phoneList.get(i).get("day"));
					role2.setEndTime(LocalDateTime.now().plusDays(day));
					role2.setRoleCode(Constant.VIP_MEMBER);
					role2.setMemberId(m2.getId());
					role2.setDelFlag(Constant.DEL_FLAG);
					memberRoleMapper.saveMemberRole(role2);

				}
				unsaveList.add(phoneList.get(i).get("phone"));
			}
		}
		return new R<>(unsaveList, MessageCodeEnum.SUCCESS.getMessage());
	}

	/**
	 * 上音图书扫码——会员注册
	 *
	 * @param phone
	 * @return
	 */
	@Override
	public Member newSave(String phone) {
		Member member = new Member();
		member.setId(IdUtil.simpleUUID());
		member.setUsername(phone);
		member.setShowname(phone);
		member.setPassword(ENCODER.encode("123456"));
		member.setPhone(phone);
		member.setCreateTime(LocalDateTime.now());
		member.setDelFlag(com.shycloud.mido.member.api.util.Constant.DEL_FLAG);
		baseMapper.insert(member);
		// 插入签到信息表
		MemberSign sign = new MemberSign();
		sign.setMemberId(member.getId());
		memberSignMapper.insert(sign);
		// 插入会员等级表
		MemberLevel level = new MemberLevel();
		level.setLevelId("1");
		level.setMemberId(member.getId());
		level.setPoints(0L);
		memberLevelMapper.insert(level);
		MemberRole role = new MemberRole();
		role.setCreateTime(LocalDateTime.now());
		role.setStartTime(LocalDateTime.now());
		role.setEndTime(LocalDateTime.now().plusMonths(1200));
		role.setRoleCode(Constant.VIP_MEMBER);
		role.setMemberId(member.getId());
		role.setDelFlag(com.shycloud.mido.member.api.util.Constant.DEL_FLAG);
		memberRoleMapper.saveMemberRole(role);
		return member;
	}

	/**
	 * 官网注册
	 *
	 * @param phone
	 * @param pwd
	 */
	@Override
	public R webRegister(String phone, String pwd) {
		//校验手机号用户名是否存在
		QueryWrapper<Member> query = new QueryWrapper<>();
		query.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
		Member entity = baseMapper.selectOne(query);
		if (null != entity) {
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_106.getMessage());
		} else {
			entity = new Member();
			entity.setUsername(phone);
			entity.setShowname(phone);
			entity.setPassword(ENCODER.encode("123456"));
			entity.setPhone(phone);
			entity.setCreateTime(LocalDateTime.now());
			entity.setDelFlag(com.shycloud.mido.organ.api.util.Constant.DEL_FLAG);
			baseMapper.insert(entity);
			// 插入签到信息表
			MemberSign sign = new MemberSign();
			sign.setMemberId(entity.getId());
			memberSignMapper.insert(sign);
			// 插入会员等级表
			MemberLevel level = new MemberLevel();
			level.setLevelId("1");
			level.setMemberId(entity.getId());
			level.setPoints(0L);
			memberLevelMapper.insert(level);
			//赠送一个月高级VIP
			MemberRole memberRole = new MemberRole();
			memberRole.setMemberId(entity.getId());
			memberRole.setRoleCode(Constant.VIP_MEMBER);
			memberRole.setDelFlag(Constant.DEL_FLAG);
			memberRole.setCreateTime(LocalDateTime.now());
			memberRole.setStartTime(LocalDateTime.now());
			memberRole.setEndTime(LocalDateTime.now().plusMonths(1));
			memberRoleMapper.saveMemberRole(memberRole);
			return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
		}
	}


}
